import { useEffect } from 'react';
import QRCode from 'qrcode.react';
import { Modal, message } from 'antd';
import { useRouter } from 'next/router';
// css
import styles from '@/styles/CommonOrder.module.scss';
import bgImg from '@/public/imgs/pay/pay-phone-bg.png';
// api
import { orderPayStatus } from '@/api/order';
import { orderCartPayStatus } from '@/api/cart';

let timer = null;

const PayModal = ({ target, orderId, codeUrl, visible, setVisible }) => {

    const router = useRouter();
    
    useEffect(() => {
        // 轮询，获取订单状态是否已支付
        // 若支付，则跳转到成功支付页面
        // 否则，不作为
        if(visible){
            timer = setInterval(() => {
                // 购物车支付
                if(target === '/'){
                    orderCartPayStatus(orderId).then(res => {
                        const { code, data } = res;
                        if(code === 0 && data == 1){
                            message.success('支付成功');
                            router.push(`/pay_success?redirect=${target}`);
                        }
                    })
                }else{
                    orderPayStatus(orderId).then(res => {
                        const { code, data } = res;
                        if(code === 0 && data){
                            if(data.orderStatus === 20){
                                message.success('支付成功');
                                router.push(`/pay_success?redirect=${target}`);
                            }
                        }
                    })
                }
            }, 2000)
        }else{
            clearInterval(timer);
        }
        
        return function () {
            clearInterval(timer);
        }
    }, [visible]);
    
    // 关闭支付
    function closePay() {
        setVisible(false);
        clearInterval(timer);
        if(router.route.includes('/[...order]') || router.route.includes('/shopping_cart/order')){
            router.replace('/personal/order');
        }
    }

    return (
        <Modal
            className={[styles['pay-modal'], 'no-footer'].join(' ')}
            centered
            width={830}
            keyboard={false}
            maskClosable={false}
            visible={visible}
            onCancel={() => { closePay() }}
        >
            <h3>微信支付</h3>
            <div className={styles['ewm']}>
                <QRCode value={codeUrl} size={300} />
                <p>请使用微信扫一扫 <br/> 扫描二维码支付</p>
            </div>
            <div className={styles['bg']}>
                <img src={process.env.basePath + bgImg.src} alt="" />
            </div>
        </Modal>
    )
}

export default PayModal;